
//
// 120318 - AH - (Garage) Created.
// 120704 - AH - (Chaos *) Removed commented away code.
// 120707 - AH - (Kryddar) Took UPLOAD_FILE_NAME, FOLDER_ID, FILE_USE, 
//               FILE_TYPE, TEXT_FILE and FILE in use.
//

package org.soekrat.server.servlets.file;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.DbFile;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements request to store file content as binary data.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class FileUploadHttpServlet extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public FileUploadHttpServlet(){}
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    PrintWriter pw=printSimpleHtmlStart(res);
    pw.println(def.compileApiHtml());
    printSimpleHtmlEnd(pw);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    handleRequest(req, res);
  }

  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    try 
    {
      // Create a new file upload handler
      ServletFileUpload upload=new ServletFileUpload();
      
      Map<String, String> fp=new HashMap<String, String>();
      
      byte[] data=null;
      
      boolean hasLoadedFile=false;
      
      // Parse the request
      FileItemIterator iter=upload.getItemIterator(req);
      while (iter.hasNext()) 
      {
        FileItemStream item=iter.next();
        
        InputStream is=item.openStream();
        
        if (item.isFormField()) 
        {
          String fname=item.getFieldName();
          String value=Streams.asString(is);
          
          value=(value==null) ? "" : value.trim();
          value=(value.length()==0) ? null : value;
          
          if (value!=null) fp.put(fname, value);
        }
        else
        {
          if (hasLoadedFile)
          {
            respond(res, "Only one file upload supported");
            return;
          }
          
          data=readBytes(is);
          
          hasLoadedFile=true;
        }
      }
      
      if (data==null)
      {
        respond(res, "No data loaded");
        return;
      }
      
      SoekratDAO dao=new SoekratDAOFactory().create();
      
      String folderKeyP=FOLDER_ID.name();
      Long folderKey=getMandatoryStringAsNonNegLong(folderKeyP, 
        fp.get(folderKeyP), res);
      if (folderKey==null) return;
      
      boolean text=fp.containsKey(TEXT_FILE.name());
      
      String name=fp.get(UPLOAD_FILE_NAME.name());
      name=(name==null) ? "" : name.trim();
      if (name.length()==0)
      {
        respond(res, "Missing name parameter");
        return;
      }
      
      String type=fp.get(FILE_TYPE.name());
      type=(type==null) ? "" : type.trim();
      type=(type.length()==0) ? null : type;
      
      String use=fp.get(FILE_USE.name());
      use=(use==null) ? "" : use.trim();
      use=(use.length()==0) ? null : use;
      
      DbFile file=dao.createFile(name, folderKey, data, text, type, -1, use);
      
      respond(res, file);
    } 
    catch (FileUploadException e)
    {
      throw new ServletException("Cannot parse multipart request.", e);
    }  
  }
 
  @SuppressWarnings("unused")
  private static void printParamMap(Map<String, String> map, PrintWriter pw)
  {
    for (Map.Entry<String, String> curr : map.entrySet())
    {
      pw.println(curr.getKey()+"="+curr.getValue());
    }
    pw.flush();
  }
 
  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef(true, "file_upload").desc("Upload File")
      .enctype("multipart/form-data").parameter(UPLOAD_FILE_NAME)
      .parameter(FOLDER_ID).parameter(FILE_USE).parameter(FILE_TYPE)
      .parameter(TEXT_FILE).parameter(FILE);
  }
  
}
